package cn.kgm.config;

import cn.kgm.io.Resources;
import cn.kgm.pojo.Configuration;
import com.alibaba.druid.pool.DruidDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 专门解析配置文件的对象
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用dom4j +  xpath解析配置文件,封装Configuration对象
     * xpath表达式:https://www.runoob.com/xpath/xpath-syntax.html
     *
     * @param inputStream
     * @return
     */
    public Configuration parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        Properties properties = new Properties();
        List<Element> propertys = rootElement.selectNodes("//property");
        for (Element element : propertys) {
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name, value);
        }

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getProperty("driverClassName"));
        druidDataSource.setUrl(properties.getProperty("url"));
        druidDataSource.setUsername(properties.getProperty("username"));
        druidDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(druidDataSource);

        List<Element> mappers = rootElement.selectNodes("//mapper");
        for (Element mapper : mappers) {
            String resouce = mapper.attributeValue("resouce");
            InputStream mapperResourceAsStream = Resources.getResourceAsStream(resouce);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(mapperResourceAsStream);
        }


        return this.configuration;
    }
}
